package com.jumi.microservice.api;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.redis.RedisCache;
import com.jumi.microservice.common.utils.ObjectUtils;
import com.jumi.microservice.constant.*;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.mapper.*;
import com.jumi.microservice.service.BasicDataService;
import com.jumi.microservice.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * - - - - - - - - - - - - - - -
 *
 * @author liuz
 * @date 2020/9/7 16:23
 * ToDoSomeThing
 * - - - - - - - - - - - - - - -
 */
@DubboService
public class BasicDataServiceImpl implements BasicDataService {

    private static final Logger logger = LoggerFactory.getLogger(BasicDataServiceImpl.class);

    @Autowired
    private FreightTemplateMapper freightTemplateMapper;

    @Autowired
    private FreightTemplateExtendMapper freightTemplateExtendMapper;

    /**
     * 商品管理mapper组件
     */
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 商品SKU管理mapper组件
     */
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;

    /**
     * 商品品牌管理mapper组件
     */
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 商品分类管理mapper组件
     */
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 商品sku管理service组件
     */
    @Autowired
    private GoodsSkuService goodsSkuService;

    /**
     * 库存管理service组件
     */
    @DubboReference
    private GoodsInventoryApi goodsInventoryApi;

    @Autowired
    private CommodityMaterialSkuRelationshipMapper commodityMaterialSkuRelationshipMapper;

    @Autowired
    private CommodityMaterialSpuRelationshipMapper commodityMaterialSpuRelationshipMapper;

    /**
     * 商品sku属性值管理mapper组件
     */
    @Autowired
    private GoodsSkuPropertyValueMapper goodsSkuPropertyValueMapper;

    @Autowired
    private CategoryService categoryService;

    /**
     * 商品spu管理service组件
     */
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 商品分类名称标识符
     */
    private static final String CATEGORY_IDENTIFIER = ">";

    /**
     * 商品spu和税收对应关系mapper组件
     */
    @Autowired
    private GoodsTaxMapper goodsTaxMapper;

    /**
     * 获取运费模板信息
     *
     * @param id 运费模板主键id
     * @return
     */
    @Override
    public FreightTempDTO freightInfo(Long id) {
        //获取模板信息
        FreightTemplateDO ftDO = freightTemplateMapper.selectOne(
                Wrappers.<FreightTemplateDO>lambdaQuery()
                        .eq(FreightTemplateDO::getId, id)
                        .eq(FreightTemplateDO::getIsDel, StatusEnum.STATUS_NO.getCode()));
        ExceptionEnum.FAIL_FREIGHT_NULL.doThrowIf(ftDO == null);
        //获取模板的详情
        List<FreightTemplateExtendDO> dos = freightTemplateExtendMapper.selectList(
                Wrappers.<FreightTemplateExtendDO>lambdaQuery()
                        .eq(FreightTemplateExtendDO::getTemplateId, id));
        return new FreightTempDTO(ftDO.getId(), ftDO.getTemplateName(), ftDO.getRule(), pos2Dtos(dos));
    }

    /**
     * 根据skuid集合查询该skuID的基本信息(库存服务)
     *
     * @param skuIds 商品skuid集合
     * @return 该skuID基本信息
     */
    @Override
    public Map<Long, SkuDTO> getSkuInfoByIds(List<Long> skuIds) {
        Map<Long, SkuDTO> skuMap = new HashMap<>(skuIds.size());

        if (skuIds.size() != 0) {
            List<GoodsSkuDTO> goodsSkuDtos = goodsSkuService.listGoodsSkuByIds(skuIds);
            for (GoodsSkuDTO goodsSkuDto : goodsSkuDtos) {
                SkuDTO skuDto = new SkuDTO();
                skuDto.setId(goodsSkuDto.getId());
                skuDto.setGoodsId(goodsSkuDto.getGoodsId());
                skuDto.setGoodsName(goodsSkuDto.getGoodsName());
                skuDto.setSpecName(goodsSkuDto.getSpecName());
                skuDto.setGoodsPropertyImage(goodsSkuDto.getGoodsPropertyImage());
                skuDto.setSupplyId(goodsSkuDto.getSupplyId());
                skuDto.setGoodsPrice(goodsSkuDto.getGoodsPrice());
                skuDto.setPlatinumPrice(goodsSkuDto.getPlatinumPrice());
                skuDto.setDiamondsPrice(goodsSkuDto.getDiamondsPrice());
                skuDto.setKingPrice(goodsSkuDto.getKingPrice());
                skuDto.setGetOrderPrice(goodsSkuDto.getGetOrderPrice());
                skuDto.setGoodsCostprice(goodsSkuDto.getGoodsCostprice());
                skuDto.setGoodsGrossWeight(goodsSkuDto.getWeight());
                skuDto.setCateId(goodsSkuDto.getCateId());
                GoodsDO goodsDo = goodsMapper.selectById(skuDto.getGoodsId());
                FreightTempDTO freightTempDTO = freightInfo(goodsDo.getTransportId());
                skuDto.setFreightTempDTO(freightTempDTO);
                skuDto.setGoodsType(goodsDo.getGoodsType());
                skuDto.setDrainage(goodsDo.getIsYinliu());
                skuDto.setIsImport(goodsDo.getIsImport());
                skuDto.setGoodCountry(goodsDo.getGoodCountry());
                skuDto.setFixRebate(goodsDo.getFixRebate());
                skuMap.put(goodsSkuDto.getId(), skuDto);
            }
        }
        return skuMap;
    }

    /**
     * 根据skuid集合或者物料名称查询该sku的基本信息
     *
     * @param skuIds     商品skuid集合、supplyName物料名称
     * @param supplyName supplyName物料名称
     * @return 该skuID基本信息
     */
    @Override
    public Map<Long, SkuDTO> getSkuInfoByIds(List<Long> skuIds, String supplyName) {
        Map<Long, SkuDTO> skuMap = new HashMap<>();
        if (skuIds != null && skuIds.size() > 0 && StringUtils.isBlank(supplyName)) {
            List<GoodsSkuDTO> goodsSkuDtos = goodsSkuService.listGoodsSkuByIds(skuIds);
            for (GoodsSkuDTO goodsSkuDto : goodsSkuDtos) {
                SkuDTO skuDto = new SkuDTO();
                skuDto.setId(goodsSkuDto.getId());
                GoodsDO goodsDO = goodsMapper.selectById(goodsSkuDto.getGoodsId());
                if (goodsDO.getGoodsType().equals(GoodsType.SINGLE)) {
                    skuDto.setMaterialName(goodsDO.getMaterialSpuName());
                    skuDto.setMaterialCount(NumberConstant.NUMBER_ONE.intValue());
                } else {
                    LambdaQueryWrapper<CommodityMaterialSkuRelationshipDO> supplySkuRelationshipWrapper = Wrappers.lambdaQuery();
                    supplySkuRelationshipWrapper.eq(CommodityMaterialSkuRelationshipDO::getSkuId, goodsSkuDto.getId());
                    List<CommodityMaterialSkuRelationshipDO> commoditySupplySkuRelationships =
                            commodityMaterialSkuRelationshipMapper.selectList(supplySkuRelationshipWrapper);

                    Set<String> supplySpuNameSet = new HashSet<>();
                    Integer supplyCount = NumberConstant.NUMBER_ZERO.intValue();
                    for (CommodityMaterialSkuRelationshipDO supplySkuRelationship : commoditySupplySkuRelationships) {
                        supplyCount += supplySkuRelationship.getComposeNumber();
                        supplySpuNameSet.add(supplySkuRelationship.getMaterialSpuName());
                    }
                    skuDto.setMaterialName(String.join(",", supplySpuNameSet));
                    skuDto.setMaterialCount(supplyCount);
                }
                skuDto.setNoDeliveryRegion(goodsDO.getNoDeliveryRegionId());
                skuMap.put(goodsSkuDto.getId(), skuDto);
            }
        }

        if (skuIds != null && skuIds.isEmpty() && !StringUtils.isBlank(supplyName)) {
            LambdaQueryWrapper<CommodityMaterialSpuRelationshipDO> materialSpuWrapper = Wrappers.lambdaQuery();
            materialSpuWrapper.like(CommodityMaterialSpuRelationshipDO::getMaterialSpuName, supplyName);

            List<CommodityMaterialSpuRelationshipDO> commodityMaterialSpuRelationships = commodityMaterialSpuRelationshipMapper.selectList(materialSpuWrapper);

            for (CommodityMaterialSpuRelationshipDO commodityMaterialSpuRelationship : commodityMaterialSpuRelationships) {
                GoodsDO goodsDO = goodsMapper.selectById(commodityMaterialSpuRelationship.getSpuId());
                List<GoodsSkuDTO> goodsSkus = goodsSkuService.listGoodsSku(goodsDO.getId());

                for (GoodsSkuDTO goodsSku : goodsSkus) {
                    SkuDTO skuDto = new SkuDTO();
                    skuDto.setId(goodsSku.getId());

                    if (goodsDO.getGoodsType().equals(GoodsType.SINGLE)) {
                        skuDto.setMaterialName(commodityMaterialSpuRelationship.getMaterialSpuName());
                        skuDto.setMaterialCount(NumberConstant.NUMBER_ONE.intValue());
                    } else {
                        LambdaQueryWrapper<CommodityMaterialSkuRelationshipDO> supplySkuRelationshipWrapper = Wrappers.lambdaQuery();
                        supplySkuRelationshipWrapper.eq(CommodityMaterialSkuRelationshipDO::getSkuId, goodsSku.getId());
                        List<CommodityMaterialSkuRelationshipDO> commoditySupplySkuRelationships = commodityMaterialSkuRelationshipMapper.selectList(supplySkuRelationshipWrapper);

                        if (Objects.isNull(commoditySupplySkuRelationships)) {
                            continue;
                        }

                        Set<String> supplySpuNameSet = new HashSet<>();
                        Integer supplyCount = NumberConstant.NUMBER_ZERO.intValue();
                        for (CommodityMaterialSkuRelationshipDO supplySkuRelationship : commoditySupplySkuRelationships) {
                            supplyCount += (supplySkuRelationship.getComposeNumber() == null ? 0 : supplySkuRelationship.getComposeNumber());
                            supplySpuNameSet.add(supplySkuRelationship.getMaterialSpuName());
                        }
                        skuDto.setMaterialName(String.join(",", supplySpuNameSet));
                        skuDto.setMaterialCount(supplyCount);
                    }
                    skuDto.setNoDeliveryRegion(goodsDO.getNoDeliveryRegionId());
                    skuMap.put(goodsSku.getId(), skuDto);
                }
            }
        }
        return skuMap;
    }

    /**
     * 根据skuid集合查询该skuID以及对应的物料信息
     *
     * @param skuIds 商品skuid集合
     * @return skuID以及对应的物料信息
     */
    @Override
    public List<GoodsSkuMaterialDTO> getMaterialSkuRelationshipByIds(List<Long> skuIds) {
        List<GoodsSkuMaterialDTO> skuMaterials = new ArrayList<>();

        for (Long skuId : skuIds) {
            GoodsSkuDO goodsSkuDO = goodsSkuMapper.selectById(skuId);
            GoodsDO goodsDO = goodsMapper.selectById(goodsSkuDO.getGoodsId());

            GoodsSkuMaterialDTO skuMaterialDTO = new GoodsSkuMaterialDTO();
            skuMaterialDTO.setSkuId(skuId);
            List<MaterialSkuRelationshipDTO> materialSkuRelationship = new ArrayList<>();
            if (goodsDO.getGoodsType().equals(GoodsType.SINGLE)) {
                MaterialSkuRelationshipDTO materialSkuRelationshipDTO = new MaterialSkuRelationshipDTO();
                materialSkuRelationshipDTO.setSkuId(skuId);
                materialSkuRelationshipDTO.setMaterialSkuId(goodsSkuDO.getMaterialSkuId());
                materialSkuRelationshipDTO.setMaterialSkuCode(goodsSkuDO.getMaterialSkuCode());
                materialSkuRelationshipDTO.setMaterialSpuId(goodsDO.getMaterialSpuId());
                materialSkuRelationshipDTO.setMaterialSpuCode(goodsDO.getMaterialSpuCode());
                materialSkuRelationshipDTO.setMaterialSpuName(goodsDO.getMaterialSpuName());
                materialSkuRelationshipDTO.setWdtGoodsId(goodsDO.getWdtGoodsId());
                materialSkuRelationshipDTO.setSupplyId(goodsDO.getSupplyId());
                materialSkuRelationshipDTO.setSupplier(goodsDO.getSupplier());
                materialSkuRelationshipDTO.setWeight(goodsSkuDO.getWeight());
                materialSkuRelationshipDTO.setQualityTime(goodsSkuDO.getQualityTime());
                materialSkuRelationshipDTO.setComposeNumber(NumberConstant.NUMBER_ONE.intValue());

                LambdaQueryWrapper<CommodityMaterialSpuRelationshipDO> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(CommodityMaterialSpuRelationshipDO::getSpuId, goodsDO.getId());
                wrapper.eq(CommodityMaterialSpuRelationshipDO::getMaterialSpuId, goodsDO.getMaterialSpuId());
                CommodityMaterialSpuRelationshipDO commodityMaterialSpuRelationship = commodityMaterialSpuRelationshipMapper.selectOne(wrapper);
                if (commodityMaterialSpuRelationship != null) {
                    materialSkuRelationshipDTO.setUnitId(commodityMaterialSpuRelationship.getUnitId());
                    materialSkuRelationshipDTO.setUnitName(commodityMaterialSpuRelationship.getUnitName());
                }

         /*       LambdaQueryWrapper<GoodsSkuPropertyValueDO> goodsSkuPropertyValueWrapper = Wrappers.lambdaQuery();
                goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getGoodsSkuId, skuId);
                goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getMaterialSkuId, goodsSkuDO.getMaterialSkuId());
                List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues = goodsSkuPropertyValueMapper.selectList(goodsSkuPropertyValueWrapper);
                materialSkuRelationshipDTO.setGoodsSkuPropertyValue(convertGoodsSkuPropertyValueList2DtoList(goodsSkuPropertyValues));
*/
                materialSkuRelationship.add(materialSkuRelationshipDTO);
            } else {
                LambdaQueryWrapper<CommodityMaterialSkuRelationshipDO> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(CommodityMaterialSkuRelationshipDO::getSkuId, skuId);

                List<CommodityMaterialSkuRelationshipDO> materialSkuRelationships =
                        commodityMaterialSkuRelationshipMapper.selectList(wrapper);

                for (CommodityMaterialSkuRelationshipDO skuRelationship : materialSkuRelationships) {
                    MaterialSkuRelationshipDTO materialSkuRelationshipDTO = new MaterialSkuRelationshipDTO();

                    materialSkuRelationshipDTO.setSkuId(skuId);
                    materialSkuRelationshipDTO.setMaterialSkuId(skuRelationship.getMaterialSkuId());
                    materialSkuRelationshipDTO.setMaterialSkuCode(skuRelationship.getMaterialSkuCode());
                    materialSkuRelationshipDTO.setMaterialSpuId(skuRelationship.getMaterialSpuId());
                    materialSkuRelationshipDTO.setMaterialSpuCode(skuRelationship.getMaterialSpuCode());
                    materialSkuRelationshipDTO.setMaterialSpuName(skuRelationship.getMaterialSpuName());
                    materialSkuRelationshipDTO.setWdtGoodsId(skuRelationship.getWdtGoodsId());
                    materialSkuRelationshipDTO.setSupplyId(skuRelationship.getSupplyId());
                    materialSkuRelationshipDTO.setSupplier(skuRelationship.getSupplier());
                    materialSkuRelationshipDTO.setWeight(skuRelationship.getWeight());
                    materialSkuRelationshipDTO.setQualityTime(skuRelationship.getQualityTime());
                    materialSkuRelationshipDTO.setComposeNumber(skuRelationship.getComposeNumber());

                    LambdaQueryWrapper<CommodityMaterialSpuRelationshipDO> cmsrQueryWrapper = Wrappers.lambdaQuery();
                    cmsrQueryWrapper.eq(CommodityMaterialSpuRelationshipDO::getSpuId, skuId);
                    cmsrQueryWrapper.eq(CommodityMaterialSpuRelationshipDO::getMaterialSpuId, goodsDO.getMaterialSpuId());

                    CommodityMaterialSpuRelationshipDO commodityMaterialSpuRelationship = commodityMaterialSpuRelationshipMapper.selectOne(cmsrQueryWrapper);
                    if (commodityMaterialSpuRelationship != null) {
                        materialSkuRelationshipDTO.setUnitId(commodityMaterialSpuRelationship.getUnitId());
                        materialSkuRelationshipDTO.setUnitName(commodityMaterialSpuRelationship.getUnitName());
                    }

              /*      LambdaQueryWrapper<GoodsSkuPropertyValueDO> goodsSkuPropertyValueWrapper = Wrappers.lambdaQuery();
                    goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getGoodsSkuId, skuId);
                    goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getMaterialSkuId, skuRelationship.getMaterialSkuId());
                    List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues = goodsSkuPropertyValueMapper.selectList(goodsSkuPropertyValueWrapper);
                    materialSkuRelationshipDTO.setGoodsSkuPropertyValue(convertGoodsSkuPropertyValueList2DtoList(goodsSkuPropertyValues));*/

                    materialSkuRelationship.add(materialSkuRelationshipDTO);
                }
            }

            skuMaterialDTO.setMaterialSkuRelationship(materialSkuRelationship);
            skuMaterials.add(skuMaterialDTO);
        }
        return skuMaterials;
    }

    /**
     * 根据spuid集合查询该spu ID，图片，名称，重量/个(订单模块)
     *
     * @param goodsIds 商品spuid集合
     * @return 该spu ID，图片，名称，重量/个
     */
    @Override
    public List<GoodsInfoDTO> getGoodsInfoByIds(List<Long> goodsIds) {
        List<GoodsDO> goodsList = null;
        if (goodsIds == null) {
            goodsList = goodsMapper.selectList(Wrappers.<GoodsDO>lambdaQuery());
        } else {
            if (goodsIds.size() > NumberConstant.NUMBER_ZERO.intValue()) {
                goodsList = goodsMapper.selectList(Wrappers.<GoodsDO>lambdaQuery().in(GoodsDO::getId, goodsIds));
            }
        }
        List<GoodsInfoDTO> goodsSpus = new ArrayList<>();
        if (goodsList != null) {
            for (GoodsDO goods : goodsList) {
                GoodsInfoDTO goodsSpu = new GoodsInfoDTO();
                goodsSpu.setId(goods.getId());
                goodsSpu.setGoodsType(goods.getGoodsType());
                goodsSpu.setGoodsName(goods.getGoodsName());
                goodsSpu.setGoodsImage(goods.getGoodsImage());

                LambdaQueryWrapper<GoodsSkuDO> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(GoodsSkuDO::getGoodsId, goods.getId());
                List<GoodsSkuDO> goodsSkus = goodsSkuMapper.selectList(wrapper);

                if (goodsSkus != null) {
                    goodsSkus.sort((x, y) -> Double.compare(x.getWeight().doubleValue(), y.getWeight().doubleValue()));
                    if (goodsSkus.size() == NumberConstant.NUMBER_ONE.intValue()) {
                        goodsSpu.setWeight(goodsSkus.get(NumberConstant.NUMBER_ZERO.intValue()).getWeight());
                    } else if (goodsSkus.size() > NumberConstant.NUMBER_ONE.intValue()) {
                        goodsSpu.setWeight(goodsSkus.get(goodsSkus.size() - NumberConstant.NUMBER_ONE.intValue()).getWeight());
                    }
                }
                String firstCreatgroyName = categoryMapper.selectById(goods.getCreatgroyFirst()).getCategoryName();
                String secondCreatgroyName = categoryMapper.selectById(goods.getCreatgroySecond()).getCategoryName();
                goodsSpu.setCategoryName(firstCreatgroyName + ">" + secondCreatgroyName);
                goodsSpu.setBrandName(brandMapper.selectById(goods.getBrandId()).getBrandName());

                Integer goodsState = goods.getGoodsState();
                if (goodsState.equals(GoodsStatus.PUTTED_ON_SHELVES.getCode())) {
                    goodsSpu.setGoodsState(GoodsStatus.PUTTED_ON_SHELVES.getDesc());
                } else if (goodsState.equals(GoodsStatus.PULLED_OFF_SHELVES.getCode())) {
                    goodsSpu.setGoodsState(GoodsStatus.PULLED_OFF_SHELVES.getDesc());
                } else if (goodsState.equals(GoodsStatus.FIX_PUTTED_ON_SHELVES.getCode())) {
                    goodsSpu.setGoodsState(GoodsStatus.FIX_PUTTED_ON_SHELVES.getDesc());
                } else {
                    goodsSpu.setGoodsState(GoodsStatus.UNKNOWN.getDesc());
                }
                goodsSpus.add(goodsSpu);
            }
        }
        return goodsSpus;
    }

    /**
     * 根据spuid集合查询该spu ID，图片，名称，重量/个
     *
     * @return 所有spu ID，图片，名称，重量/个
     */
    @Override
    public List<GoodsInfoDTO> getGoodsInfoByIds() {
        List<GoodsDO> goodsList = goodsMapper.selectList(
                Wrappers.<GoodsDO>lambdaQuery()
                        .eq(GoodsDO::getIsDel, StatusEnum.STATUS_NO.getCode()));
        return convertGoodsDoList2DtoList(goodsList);
    }

    /**
     * 根据skuid集合查询该skuID的属性
     *
     * @param skuIds 商品skuid集合
     * @return 该skuID集合的属性
     */
    @Override
    public List<SkuDTO> getGoodsSkuListByIds(List<Long> skuIds) {
        List<SkuDTO> skuList = new ArrayList<>();

        if (skuIds.size() != NumberConstant.NUMBER_ZERO.intValue()) {
            List<GoodsSkuDTO> goodsSkuDtos = goodsSkuService.listGoodsSkuByIds(skuIds);
            //List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(skuIds);
            for (GoodsSkuDTO goodsSkuDto : goodsSkuDtos) {
                SkuDTO skuDto = new SkuDTO();
                skuDto.setId(goodsSkuDto.getId());
                skuDto.setGoodsId(goodsSkuDto.getGoodsId());
                skuDto.setGoodsName(goodsSkuDto.getGoodsName());
                skuDto.setGoodsPropertyImage(goodsSkuDto.getGoodsPropertyImage());
                skuDto.setSupplyId(goodsSkuDto.getSupplyId());
                skuDto.setGoodsPrice(goodsSkuDto.getGoodsPrice());
                skuDto.setPlatinumPrice(goodsSkuDto.getPlatinumPrice());
                skuDto.setDiamondsPrice(goodsSkuDto.getDiamondsPrice());
                skuDto.setKingPrice(goodsSkuDto.getKingPrice());
                skuDto.setGetOrderPrice(goodsSkuDto.getGetOrderPrice());
                skuDto.setGoodsCostprice(goodsSkuDto.getGoodsCostprice());
                skuDto.setGoodsGrossWeight(goodsSkuDto.getWeight());

                List<GoodsSkuDO> goodsSkuList = goodsSkuMapper.selectList(
                        Wrappers.<GoodsSkuDO>lambdaQuery()
                                .select(GoodsSkuDO::getId)
                                .eq(GoodsSkuDO::getIsDel, StatusEnum.STATUS_NO.getCode())
                                .eq(GoodsSkuDO::getGoodsId, skuDto.getGoodsId()));
                List<Long> skuIdList = new ArrayList<>();
                goodsSkuList.forEach(goodsSkuDO -> skuIdList.add(goodsSkuDO.getId()));
                List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(skuIdList);
                long spuStock = NumberConstant.NUMBER_ONE;
                if (goodsSpuInventories != null) {
                    for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
                        spuStock += goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                        if (goodsSkuDto.getId().equals(goodsSpuInventory.getSkuId())) {
                            Integer stock = goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                            skuDto.setSaleStockQuantity(stock);
                        }
                    }
                } else {
                    skuDto.setSaleStockQuantity(NumberConstant.NUMBER_ZERO.intValue());
                }

                GoodsDO goodsDo = goodsMapper.selectById(skuDto.getGoodsId());
                if (goodsDo.getGoodsState().equals(GoodsStatus.PULLED_OFF_SHELVES.getCode())
                        || goodsSkuDto.getIsDel().equals(StatusEnum.STATUS_YES.getCode())
                        || goodsDo.getIsImport().equals(NumberConstant.NUMBER_ONE.intValue())
                        || spuStock == NumberConstant.NUMBER_ONE) {
                    skuDto.setInvalid(Boolean.TRUE);
                }
                skuDto.setGoodsType(goodsDo.getGoodsType());
                skuDto.setIsImport(goodsDo.getIsImport());

                LambdaQueryWrapper<GoodsSkuPropertyValueDO> goodsSkuPropertyValueWrapper = Wrappers.lambdaQuery();
                goodsSkuPropertyValueWrapper.eq(GoodsSkuPropertyValueDO::getGoodsSkuId, goodsSkuDto.getId());

                List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues = goodsSkuPropertyValueMapper.selectList(goodsSkuPropertyValueWrapper);
                List<GoodsSkuPropertyValueDTO> goodsSkuPropertyValueDtos = convertGoodsSkuPropertyValueList2DtoList(goodsSkuPropertyValues);
                skuDto.setGoodsSkuPropertyValue(goodsSkuPropertyValueDtos);

                skuList.add(skuDto);
            }
        }
        return skuList;
    }

    /**
     * 活动添加商品分页列表
     *
     * @param queryJson 商品条件类
     * @return
     */
    @Override
    public TableDataInfo<GoodsSpuDTO> getGoods4ActivityPage(String queryJson) {
        QueryActivityGoodsDTO queryActivityGoods = JSON.toJavaObject(JSONObject.parseObject(queryJson), QueryActivityGoodsDTO.class);
        TableDataInfo<GoodsSpuDTO> tableDataInfo = new TableDataInfo<>();
        List<GoodsSpuDTO> goodsSpus = new ArrayList<>();

        LambdaQueryWrapper<GoodsDO> goodsWrapper = Wrappers.lambdaQuery();
        goodsWrapper.eq(GoodsDO::getIsDel, StatusEnum.STATUS_NO.getCode());
        goodsWrapper.eq(queryActivityGoods.getSupplyId() != null, GoodsDO::getSupplyId, queryActivityGoods.getSupplyId());
        goodsWrapper.eq(queryActivityGoods.getCategoryId() != null, GoodsDO::getCreatgroySecond, queryActivityGoods.getCategoryId());
        goodsWrapper.like(!org.apache.commons.lang.StringUtils.isBlank(queryActivityGoods.getKeyWord()), GoodsDO::getGoodsName, queryActivityGoods.getKeyWord());
        //添加活动 过滤已经添加过活动的spuid
        goodsWrapper.notIn(CollectionUtil.isNotEmpty(queryActivityGoods.getSpuIds()), GoodsDO::getId, queryActivityGoods.getSpuIds());
        goodsWrapper.eq(queryActivityGoods.getBrandId()!=null, GoodsDO::getBrandId, queryActivityGoods.getBrandId());
        goodsWrapper.orderByDesc(GoodsDO::getId);

        IPage<GoodsDO> goodsDoPage = new Page<>(queryActivityGoods.getPageNum(), queryActivityGoods.getPageSize());
        goodsDoPage = goodsMapper.selectPage(goodsDoPage, goodsWrapper);

        int enableVirtualNum = redisCache.getCacheObject(GoodsKeyConstant.GOODS_VIRTUALNUM_KEY);

        for (GoodsDO goods : goodsDoPage.getRecords()) {
            GoodsSpuDTO goodsSpu = new GoodsSpuDTO();
            goodsSpu.setGoodsId(goods.getId());
            goodsSpu.setGoodsName(goods.getGoodsName());
            goodsSpu.setCategory(goods.getCreatgroyFirst());

            CategoryDTO category = categoryService.getCategoryById(goodsSpu.getCategory());
            goodsSpu.setCategoryName(category.getCategoryName());

            goodsSpu.setSecondCategory(goods.getCreatgroySecond());
            String secondCreatgroyName = categoryService.getCategoryById(goods.getCreatgroySecond()).getCategoryName();
            goodsSpu.setSecondCategoryName(category.getCategoryName() + CATEGORY_IDENTIFIER + secondCreatgroyName);

            goodsSpu.setGoodsPrice(goods.getGoodsPrice());
            goodsSpu.setGoodsMarketprice(goods.getGoodsMarketprice());
            goodsSpu.setGoodsImage(goods.getGoodsImage());
            goodsSpu.setGoodsState(goods.getGoodsState());
            goodsSpu.setSupplyId(goods.getSupplyId());
            goodsSpu.setSupplierCompanyName(goods.getSupplier());

            List<Long> skuIds = goodsService.getSkuIdListBySpuId(goods.getId());
            Integer saleStockQuantity = 0;
            Integer saledStockQuantity = 0;
            if (skuIds.size() > NumberConstant.NUMBER_ZERO.intValue()) {
                List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(skuIds);
                for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
                    saleStockQuantity += goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                    saledStockQuantity += goodsSpuInventory.getSaledStorage();
                }
            }

            if (enableVirtualNum == NumberConstant.NUMBER_ONE.intValue()) {
                Integer virtualNum = goodsSkuService.countVirtualNumBySpuId(goods.getId());
                saledStockQuantity += virtualNum;
                saleStockQuantity += virtualNum;
            }

            goodsSpu.setSaleStockQuantity(saleStockQuantity);
            goodsSpu.setSaledStockQuantity(saledStockQuantity);
            goodsSpus.add(goodsSpu);
        }
        tableDataInfo.setTotal(goodsDoPage.getTotal());
        tableDataInfo.setRows(goodsSpus);
        return tableDataInfo;
    }

    /**
     * 活动添加商品分页列表
     *
     * @param goodsIds 商品SPU ID集合
     * @return Map<Long, BigDecimal>
     */
    @Override
    public Map<Long, BigDecimal> getGoodsTaxBySpuId(List<Long> goodsIds) {
        Map<Long, BigDecimal> goodsTaxMap = new HashMap<>();
        LambdaQueryWrapper<GoodsTaxDO> goodsTaxWrapper = Wrappers.lambdaQuery();
        goodsTaxWrapper.in(GoodsTaxDO::getSpuId, goodsIds);
        List<GoodsTaxDO> goodsTaxList = goodsTaxMapper.selectList(goodsTaxWrapper);
        goodsTaxList.forEach(goodsTaxDO -> goodsTaxMap.put(goodsTaxDO.getSpuId(), goodsTaxDO.getTaxRate()));
        return goodsTaxMap;
    }

    @Override
    public Map<Long, Long> getSpuIdBySkuIds(List<Long> skuIds) {
        List<GoodsSkuDO> goodsSkus = goodsSkuMapper.selectBatchIds(skuIds);
        Map<Long, Long> sku2spuMap = new HashMap<>();
        goodsSkus.stream().forEach(goodsSkuDO -> sku2spuMap.put(goodsSkuDO.getId(), goodsSkuDO.getGoodsId()));
        return sku2spuMap;
    }

    /**
     * 根据skuid集合获取物料名称查询该sku的基本信息
     *
     * @param spuIds 商品skuid集合、supplyName物料名称
     * @param supplyName supplyName物料名称
     * @return 该skuID基本信息
     */
    @Override
    public Map<Long, SkuDTO> getMaterialInfoByIds4Order(List<Long> spuIds, String supplyName) {
        logger.info("订单调用传输的spuid集合:{}",JSONObject.toJSONString(spuIds));
        Map<Long, SkuDTO> skuMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(spuIds) && StringUtils.isBlank(supplyName)) {
//            List<GoodsSkuDTO> goodsSkuDtos = goodsSkuService.listGoodsSkuByIds(skuIds);

            //获取商品spu信息
            List<GoodsDO> goods = goodsMapper.selectList(
                    Wrappers.<GoodsDO>lambdaQuery()
                            .in(GoodsDO::getId, spuIds)
                            .in(GoodsDO::getGoodsType, 1, 3));
            //获取商品的sku物料对应关系
            LambdaQueryWrapper<CommodityMaterialSkuRelationshipDO> supplySkuRelationshipWrapper = Wrappers.lambdaQuery();
            supplySkuRelationshipWrapper.in(CommodityMaterialSkuRelationshipDO::getSpuId, spuIds);
            List<CommodityMaterialSkuRelationshipDO> allCommoditySupplySkuRelationships =
                    commodityMaterialSkuRelationshipMapper.selectList(supplySkuRelationshipWrapper);
            for (GoodsDO good : goods) {
                SkuDTO skuDto = new SkuDTO();
                skuDto.setGoodsId(good.getId());
                if (good.getGoodsType().equals(GoodsType.SINGLE)) {
                    skuDto.setMaterialName(good.getMaterialSpuName());
                    skuDto.setMaterialCount(NumberConstant.NUMBER_ONE.intValue());
                } else {
                    List<CommodityMaterialSkuRelationshipDO> commoditySupplySkuRelationships =
                            allCommoditySupplySkuRelationships.stream().filter(allComd->allComd.getSpuId().equals(good.getId())).collect(Collectors.toList());
                    if(CollectionUtil.isNotEmpty(commoditySupplySkuRelationships)) {
                        Set<String> supplySpuNameSet = new HashSet<>();
                        Integer supplyCount = NumberConstant.NUMBER_ZERO.intValue();
                        for (CommodityMaterialSkuRelationshipDO supplySkuRelationship : commoditySupplySkuRelationships) {
                            supplyCount += supplySkuRelationship.getComposeNumber();
                            supplySpuNameSet.add(supplySkuRelationship.getMaterialSpuName());
                        }
                        skuDto.setMaterialName(String.join(",", supplySpuNameSet));
                        skuDto.setMaterialCount(supplyCount);
                    }
                }
                skuDto.setNoDeliveryRegion(good.getNoDeliveryRegionId());
                skuMap.put(good.getId(), skuDto);
            }
        }

        if (CollectionUtil.isEmpty(spuIds) && StringUtils.isNotBlank(supplyName)) {
            LambdaQueryWrapper<CommodityMaterialSpuRelationshipDO> materialSpuWrapper = Wrappers.lambdaQuery();
            materialSpuWrapper.like(CommodityMaterialSpuRelationshipDO::getMaterialSpuName, supplyName);
            List<CommodityMaterialSpuRelationshipDO> commodityMaterialSpuRelationships = commodityMaterialSpuRelationshipMapper.selectList(materialSpuWrapper);
//            skuMap = commodityMaterialSpuRelationships.stream().collect(Collectors.toMap(CommodityMaterialSpuRelationshipDO::getSpuId, ));
            for (CommodityMaterialSpuRelationshipDO commodityMaterialSpuRelationship : commodityMaterialSpuRelationships) {
//                List<GoodsDO> goods = allGoods.stream().filter(allg->allg.getId().equals(commodityMaterialSpuRelationship.getSpuId())).collect(Collectors.toList());
//                for (GoodsSkuDTO goodsSku : goodsSkus) {
//                    SkuDTO skuDto = new SkuDTO();
//                    skuDto.setId(goodsSku.getId());
//
//                    if (goodsDO.getGoodsType().equals(GoodsType.SINGLE)) {
//                        skuDto.setMaterialName(commodityMaterialSpuRelationship.getMaterialSpuName());
//                        skuDto.setMaterialCount(NumberConstant.NUMBER_ONE.intValue());
//                    } else {
//                        LambdaQueryWrapper<CommodityMaterialSkuRelationshipDO> supplySkuRelationshipWrapper = Wrappers.lambdaQuery();
//                        supplySkuRelationshipWrapper.eq(CommodityMaterialSkuRelationshipDO::getSkuId, goodsSku.getId());
//                        List<CommodityMaterialSkuRelationshipDO> commoditySupplySkuRelationships = commodityMaterialSkuRelationshipMapper.selectList(supplySkuRelationshipWrapper);
//
//                        if (Objects.isNull(commoditySupplySkuRelationships)) {
//                            continue;
//                        }
//
//                        Set<String> supplySpuNameSet = new HashSet<>();
//                        Integer supplyCount = NumberConstant.NUMBER_ZERO.intValue();
//                        for (CommodityMaterialSkuRelationshipDO supplySkuRelationship : commoditySupplySkuRelationships) {
//                            supplyCount += (supplySkuRelationship.getComposeNumber() == null ? 0 : supplySkuRelationship.getComposeNumber());
//                            supplySpuNameSet.add(supplySkuRelationship.getMaterialSpuName());
//                        }
//                        skuDto.setMaterialName(String.join(",", supplySpuNameSet));
//                        skuDto.setMaterialCount(supplyCount);
//                    }
//                    skuDto.setgoo(goodsDO.getNoDeliveryRegionId());
                    skuMap.put(commodityMaterialSpuRelationship.getSpuId(), new SkuDTO());
            }
        }
        logger.info("返回订单的spu对应物料关系为:{}",JSONObject.toJSONString(skuMap));
        return skuMap;
    }

    private List<GoodsInfoDTO> convertGoodsDoList2DtoList(List<GoodsDO> goodsList) {
        List<GoodsInfoDTO> goodsInfos = null;
        try {
            goodsInfos = ObjectUtils.convertList(goodsList, GoodsInfoDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsInfos;
    }


    /**
     * 将商品sku属性 DO对象集合转换为VO对象集合
     *
     * @param goodsSkuPropertyValues 商品sku 属性DO集合
     * @return List<GoodsSkuPropertyValueDTO> 商品sku属性 DTO对象集合
     */
    private List<GoodsSkuPropertyValueDTO> convertGoodsSkuPropertyValueList2DtoList(
            List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues) {
        List<GoodsSkuPropertyValueDTO> goodsSkuPropertyValueDtos = null;
        try {
            goodsSkuPropertyValueDtos = ObjectUtils.convertList(goodsSkuPropertyValues,
                    GoodsSkuPropertyValueDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsSkuPropertyValueDtos;
    }


 /*   private List<SkuPropertyValueDTO> convertGoodsSkuPropertyValueList2DtoList(
            List<GoodsSkuPropertyValueDO> goodsSkuPropertyValues) {
        List<SkuPropertyValueDTO> goodsSkuPropertyValueDtos = null;
        try {
            goodsSkuPropertyValueDtos = ObjectUtils.convertList(goodsSkuPropertyValues,
                    SkuPropertyValueDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return goodsSkuPropertyValueDtos;
    }*/

    /**
     * pos->dtos
     *
     * @param pos
     * @return
     */
    private List<FreightTempInfoDTO> pos2Dtos(List<FreightTemplateExtendDO> pos) {
        return pos.stream().map(po -> {
            FreightTempInfoDTO dto = null;
            try {
                dto = po.clone(FreightTempInfoDTO.class);
            } catch (Exception e) {

            }
            return dto;
        }).collect(Collectors.toList());
    }
}
